# coding=utf-8
import json
from flask import make_response,request
import datetime, time, calendar
import random
import re,os,uuid
import hashlib
connection = None
def UUID():
    return str(uuid.uuid4())
def convert_to_dict(obj):
  '''把Object对象转换成Dict对象'''
  dict = {}
  dict.update(obj.__dict__)
  return dict
def convert_to_dicts(objs):
  '''把对象列表转换为字典列表'''
  obj_arr = []
  for o in objs:
    #把Object对象转换成Dict对象
    dict = {}
    dict.update(o.__dict__)
    obj_arr.append(dict)
  return obj_arr
def class_to_dict(obj):
  '''把对象(支持单个对象、list、set)转换成字典'''
  is_list = obj.__class__ == [].__class__
  is_set = obj.__class__ == set().__class__
  if is_list or is_set:
    obj_arr = []
    for o in obj:
      #把Object对象转换成Dict对象
      dict = {}
      dict.update(o.__dict__)
      obj_arr.append(dict)
    return obj_arr
  else:
    dict = {}
    dict.update(obj.__dict__)
    return dict

def obj_to_jsonstr(obj):
    cb = None
    if('callback' in request.args):
        cb = request.args.get('callback')
    content = None
    # json.dumps(obj, default=lambda o: obj.__dict__, sort_keys=True, indent=4)
    if(cb!=None):
        content = cb+"("+json.dumps(obj,ensure_ascii=False)+")" #,ensure_ascii=False
    else:
        content = json.dumps(obj,ensure_ascii=False) #,ensure_ascii=False
    response = make_response(content)
    # response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Content-Type'] = 'application/json; charset=utf-8'
    response.headers['Access-Control-Allow-Origin'] = '*'
    # response.headers['Access-Control-Allow-Methods'] = 'POST'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return response

def get_time_stamp():
    return round(time.time()*1000)

def format_time(fmt,timestamp):
    try:
        return time.strftime(fmt,time.localtime(timestamp))
    except Exception as ex:
        return timestamp

def get_time(timestamp):
    time_str = format_time('%Y-%m-%d %H:%M:%S',timestamp)
    return time.strptime(time_str,'%Y-%m-%d %H:%M:%S')
def getUniqueNum():
    nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S")  # 生成当前时间
    randomNum = random.randint(0, 100)  # 生成的随机整数n，其中0<=n<=100
    if randomNum <= 10:
        randomNum = str(0) + str(randomNum)
    uniqueNum = str(nowTime) + str(randomNum)
    return uniqueNum

def get_param(name,normal=None):
    pv = normal
    if name in request.form:
        pv = request.form[name]
        if len(pv)==0:
            pv = normal
    if request.args.get(name) != None:
        pv = request.args.get(name)
        if len(pv)==0:
            pv = normal
    return pv
def getHeader(key,normal=None):
    value = normal
    if key in request.headers:
        value = request.headers[key]
    return value
def filter_tags(htmlstr):
    if htmlstr==None:
        return ""
    re_cdata=re.compile('//<!\[CDATA\[[^>]*//\]\]>',re.I) #匹配CDATA
    re_script=re.compile('<\s*script[^>]*>[^<]*<\s*/\s*script\s*>',re.I)#Script
    re_style=re.compile('<\s*style[^>]*>[^<]*<\s*/\s*style\s*>',re.I)#style
    re_br=re.compile('<br\s*?/?>')#处理换行
    re_h=re.compile('</?\w+[^>]*>')#HTML标签
    re_comment=re.compile('<!--[^>]*-->')#HTML注释
    s=re_cdata.sub('',htmlstr)#去掉CDATA
    s=re_script.sub('',s) #去掉SCRIPT
    s=re_style.sub('',s)#去掉style
    s=re_br.sub('\n',s)#将br转换为换行
    s=re_h.sub('',s) #去掉HTML 标签
    s=re_comment.sub('',s)#去掉HTML注释
    blank_line=re.compile('\n+')
    s=blank_line.sub('\n',s)
    s = replaceCharEntity(s)  # 替换实体
    #s = s.replace(' ','')
    return s
def replaceCharEntity(htmlstr):

    CHAR_ENTITIES={'nbsp':'','160':' ', 'lt':'<','60':'<',
        'gt':'>','62':'>',
        'amp':'&','38':'&',
        'quot':'"','34':'"'}
    re_charEntity=re.compile(r'&#?(?P<name>\w+);')
    sz=re_charEntity.search(htmlstr)
    while sz:
        entity=sz.group()
        key=sz.group('name')
        try:
            htmlstr=re_charEntity.sub(CHAR_ENTITIES[key],htmlstr,1)
            sz=re_charEntity.search(htmlstr)
        except KeyError:
            htmlstr=re_charEntity.sub('',htmlstr,1)
            sz=re_charEntity.search(htmlstr)
    htmlstr = htmlstr.replace('&nbsp','')
    return htmlstr

def getMonthFirstDayAndLastDay(year=None, month=None):
    if year:
        year = int(year)
    else:
        year = datetime.date.today().year

    if month:
        month = int(month)
    else:
        month = datetime.date.today().month
    # 获取当月第一天的星期和当月的总天数
    firstDayWeekDay, monthRange = calendar.monthrange(year, month)
    starttime, endtime = get_today_date()
    # 获取当月的第一天
    firstDay = datetime.date(year=year, month=month, day=1)
    lastDay = datetime.date(year=year, month=month, day=monthRange)

    return firstDay, lastDay
def get_timestamp(timeStr,fmt='%Y-%m-%d %H:%M:%S'):
    return time.mktime(time.strptime(timeStr,fmt))

def is_alphabet(uchar):
    """判断一个unicode是否是英文字母"""
    if (uchar >= u'\u0041' and uchar <= u'\u005a') or (uchar >= u'\u0061' and uchar <= u'\u007a'):
        return True
    else:
        return False

def is_chinese(uchar):
    """判断一个unicode是否是汉字"""
    if uchar >= u'\u4e00' and uchar <= u'\u9fa5':
        return True
    else:
        return False

def getDayInweekMonday():
    week_num = datetime.datetime.now().weekday()
    Monday = datetime.datetime.now() + datetime.timedelta(days=-week_num)
    Monday = str(Monday)[0:10]
    return Monday

def hasNumbers(str):
    return any(char.isdigit() for char in str)

def getDayNum(daystr):
    ds = daystr.split("-")
    d1 = datetime.date(int(ds[0]),int(ds[1]),int(ds[2]))
    d2 = datetime.date.today()
    return d1-d2

def get_today_date():
    year = datetime.datetime.today().year
    month = datetime.date.today().month
    day = datetime.date.today().day
    today = str(year)+"-"+str(month)+"-"+str(day)
    starttime = today + ' 00:00:00'
    endtime = today + ' 23:59:59'
    return starttime,endtime
def get_today():
    year = datetime.datetime.today().year
    month = datetime.date.today().month
    day = datetime.date.today().day
    today = str(year) + "-" + str(month) + "-" + str(day)
    return today
def get_date(delta=0):
    if(delta==0):
        return get_today()
    else:
        z = datetime.datetime.today()
        z = z + relativedelta.relativedelta(days=delta)
        return z.strftime('%Y-%m-%d')
        #return str(z.year) + '-' + str(z.month) + '-' + str(z.day)
def get_today_hours():
    today = datetime.datetime.today()
    year = today.year
    month = today.month
    day = today.day
    hours = today.hour
    _today = str(year) + "-" + str(month) + "-" + str(day)+"-"+str(hours)
    return _today

def get_current_time():
    today = datetime.datetime.today()
    # year = today.year
    # month = today.month
    # day = today.day
    # hours = today.hour
    # _today = str(year) + "-" + str(month) + "-" + str(day)+" "+str(hours)+":"+str(today.minute)+':'+str(today.second)
    #return _today
    return today.strftime('%Y-%m-%d %H:%M:%S')

def get_host_ip():
    import socket
    myname = socket.getfqdn(socket.gethostname())
    myaddr = socket.gethostbyname(myname)
    return myaddr


def loadFromFile(filename):
    resultFile = os.getcwd() + '/data/' +filename
    if os.path.exists(resultFile):
        with open(resultFile) as json_file:
            obj = json.load(json_file)
            return obj_to_jsonstr(obj)
    else:
        return '{}'

'''
定位获取包含某个关键词前后文本段
'''
def get_keyword_line_text(text,keyword,text_num=30):
    text = text.decode('utf8')
    keyword = keyword.decode('utf8')
    result = re.findall(r'(' + keyword + '.+)', text)

    if result != None and len(result) > 0:
        firstMore = ""
        index = text.index(keyword)
        start=random.randint(4, text_num-4)
        if index>0 and index>start:
            firstMore="..."
            firstStr = text[index-start:index]
        else:
            firstStr=""
        _str = firstStr+result[0]
        if len(_str)>text_num:
            _str = firstMore+_str[0:text_num]+"..."
        return _str
    else:
        return text[0:text_num]

def getMonthLastDay(year=None, month=None):
    '''获取某年某月最后一天'''
    if year:
        year = int(year)
    else:
        year = datetime.date.today().year
    if month:
        month = int(month)
    else:
        month = datetime.date.today().month
        # 获取当月第一天的星期和当月的总天数
    firstDayWeekDay, monthRange = calendar.monthrange(year, month)
    lastDay = datetime.date(year=year, month=month, day=monthRange)
    return lastDay

def total_size(dir):    #计算总计大小
    size = 0
    for root, dirs, files in os.walk(dir):
        size += sum([os.path.getsize(os.path.join(root, name)) for name in files])
    return size
def mk_md5_string(src):
    m2 = hashlib.md5()
    b = src.encode(encoding='utf-8')
    m2.update(b)
    return m2.hexdigest()